package cn.com.dashihui.web.controller;

import java.io.IOException;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.kit.ValidateKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.Store;
import cn.com.dashihui.web.service.StoreService;

@RequiresAuthentication
public class StoreController extends BaseController{
	private static final Logger logger = Logger.getLogger(StoreController.class);
	private StoreService storeService = new StoreService();
    
	//@RequiresPermissions("dict:store:index")
    public void index(){
        render("index.jsp");
    }
    /**
     * 社区管理主页面的分页数据
     */
    public void page(){
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		String title = getPara("t");
		int type = getParaToInt("type",0);
		int attribute = getParaToInt("attribute",0);
		int province = getParaToInt("p",0);
		int city = getParaToInt("c",0);
		int area = getParaToInt("a",0);
		renderResult(0,storeService.findByPage(pageNum, pageSize, title, type, attribute, province, city, area));
	}

	/**
	 * 转到社区管理增加页面
	 */
	public void toAdd(){
		render("add.jsp");
	}
	
	/**
	 * 添加
	 * @return -1：异常，0：成功，1：用户名为空，2：用户名过长，3：用户已经存在，4：密码为空，5：密码过长，6：店铺名为空，7：店铺名过长，8：店长姓名为空，9：店长姓名过长......
	 */
	public void doAdd(){
		UploadFile thumb = getFile("thumb");
		//用户名
		String username = getPara("username");
		//密码
		String password = getPara("password");
		//店铺名称
		String title = getPara("title");
		//店长
		String manager = getPara("manager");
		//店铺类型
		int type = getParaToInt("type",0);
		//店铺属性
		int attribute = getParaToInt("attribute",0);
		//电话
		String tel = getPara("tel");
		//邮箱
		String mail = getPara("mail");
		//营业开始时间
		String beginTime = getPara("beginTime");
		//营业结束时间
		String endTime = getPara("endTime");
		//配送说明
		String deliverydes = getPara("deliverydes");
		//省、市、县/区
		int province = getParaToInt("province",0),city = getParaToInt("city",0),area = getParaToInt("area",0);
		//详细地址
		String address = getPara("address");
		if(StrKit.isBlank(username)){
			renderResult(1);
			return;
		}else if(username.length()>20){
			renderResult(2);
			return;
		}else if(storeService.findExistsByUsername(username)){
			renderResult(3);
			return;
		}else if(StrKit.isBlank(password)){
			renderResult(4);
			return;
		}else if(password.length()>100){
			renderResult(5);
			return;
		}else if(StrKit.isBlank(title)){
			renderResult(6);
			return;
		}else if(title.length()>50){
			renderResult(7);
			return;
		}else if(StrKit.isBlank(manager)){
			renderResult(8);
			return;
		}else if(manager.length()>20){
			renderResult(9);
			return;
		}else if(type==0){
			renderResult(10);
			return;
		}else if(attribute==0){
			renderResult(11);
			return;
		}else if(!ValidateKit.Tel(tel) && !ValidateKit.Mobile(tel)){
			renderResult(12);
			return;
		}else if(StrKit.notBlank(mail)&&!ValidateKit.Email(mail)){
			renderResult(13);
			return;
		}else if(StrKit.notBlank(deliverydes) && deliverydes.length()>255){
			renderResult(14);
			return;
		}else if(province==0||city==0||area==0){
			renderResult(15);
			return;
		}else if(StrKit.isBlank(address)){
			renderResult(16);
			return;
		}else if(address.length()>100){
			renderResult(17);
			return;
		}else{
			//保存
			Store store = new Store()
				.set("username", username)
				.set("password", new DefaultPasswordService().encryptPassword(password))
				.set("title", title)
				.set("manager", manager)
				.set("type", type)
				.set("attribute", attribute)
				.set("province", province)
				.set("city", city)
				.set("area", area)
				.set("address", address);
			//如果上传了图片，则上传至FTP，并记录图片文件名
			if(thumb!=null){
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.STORE_LOGO);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(18);
					return;
				}
				store.set("thumb", dir.concat(thumbFileName));
			}
			if(StrKit.notBlank(tel)){
				store.set("tel", tel);
			}
			if(StrKit.notBlank(mail)){
				store.set("mail", mail);
			}
			if(StrKit.notBlank(beginTime)){
				store.set("beginTime", beginTime);
			}
			if(StrKit.notBlank(endTime)){
				store.set("endTime", endTime);
			}
			if(StrKit.notBlank(deliverydes)){
				store.set("deliverydes", deliverydes);
			}
			if(storeService.addStore(store)){
				renderSuccess(storeService.findById(store.getInt("id")));
				return;
			}
		}
		renderFailed();
	}
	
	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", storeService.findById(id));
		}
		render("edit.jsp");
	}
	
	/**
	 * 更新
	 * @return -1：异常，0：成功，1：便利店名称为空，2：便利店名称过长，3：代码为空，4：代码过长，5：代码已经存在，6：详情地址为空，7：详细地址过长，8：图片为空，9：图片上传失败
	 */
	public void doEdit(){
		UploadFile thumb = getFile("thumb");
		//店铺id
		String id =  getPara("id");
		//店铺名称
		String title = getPara("title");
		//店长
		String manager = getPara("manager");
		//店铺类型
		int type = getParaToInt("type",0);
		//店铺属性
		int attribute = getParaToInt("attribute",0);
		//电话
		String tel = getPara("tel");
		//邮箱
		String mail = getPara("mail");
		//营业开始时间
		String beginTime = getPara("beginTime");
		//营业结束时间
		String endTime = getPara("endTime");
		//配送说明
		String deliverydes = getPara("deliverydes");
		//省、市、县/区
		int province = getParaToInt("province",0),city = getParaToInt("city",0),area = getParaToInt("area",0);
		//详细地址
		String address = getPara("address");
		//旧图片
		String thumbOld = getPara("thumbOld");
		if(StrKit.isBlank(id)){
			renderFailed();
			return;
		}if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>50){
			renderResult(2);
			return;
		}else if(StrKit.isBlank(manager)){
			renderResult(3);
			return;
		}else if(manager.length()>20){
			renderResult(4);
			return;
		}else if(type==0){
			renderResult(5);
			return;
		}else if(attribute==0){
			renderResult(6);
			return;
		}else if(StrKit.notBlank(tel) && !ValidateKit.Tel(tel) && !ValidateKit.Mobile(tel)){
			renderResult(7);
			return;
		}else if(StrKit.notBlank(mail) && !ValidateKit.Email(mail)){
			renderResult(8);
			return;
		}else if(StrKit.notBlank(deliverydes) && deliverydes.length()>200){
			renderResult(11);
			return;
		}else if(province==0||city==0||area==0){
			renderResult(12);
			return;
		}else if(StrKit.isBlank(address)){
			renderResult(13);
			return;
		}else if(address.length()>100){
			renderResult(14);
			return;
		}else{
			//更新
			int storeid = Integer.valueOf(id).intValue();
			Store store = new Store()
				.set("id", storeid)
				.set("title", title)
				.set("manager", manager)
				.set("type", type)
				.set("attribute", attribute)
				.set("province", province)
				.set("city", city)
				.set("area", area)
				.set("address", address);
			if(thumb!=null){
				//如果修改了图片，则上传新图片，删除旧图片
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.STORE_LOGO);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
					deleteFromFtp(thumbOld);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(6);
					return;
				}
				store.set("thumb", dir.concat(thumbFileName));
			}
			if(StrKit.notBlank(tel)){
				store.set("tel", tel);
			}
			if(StrKit.notBlank(mail)){
				store.set("mail", mail);
			}
			if(StrKit.notBlank(beginTime)){
				store.set("beginTime", beginTime);
			}
			if(StrKit.notBlank(endTime)){
				store.set("endTime", endTime);
			}
			if(StrKit.notBlank(deliverydes)){
				store.set("deliverydes", deliverydes);
			}
			if(storeService.editStore(store)){
				renderSuccess(storeService.findById(Integer.valueOf(id)));
				return;
			}
		}
		renderFailed();
	}
	
	public void toEditPwd(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", storeService.findById(id));
		}
		render("editPwd.jsp");
	}
	
	/**
	 * 更新密码
	 * @return -1：异常，0：成功，1：密码为空，2：密码过长
	 */
	public void doEditPwd(){
		//店铺ID
		String storeid = getPara("storeid");
		//密码
		String password = getPara("password");
		if(StrKit.isBlank(storeid)){
			renderFailed();
			return;
		}else if(StrKit.isBlank(password)){
			renderResult(1);
			return;
		}else if(password.length()>100){
			renderResult(2);
			return;
		}else{
			//更新
			if(storeService.editStore(new Store()
				.set("id", storeid)
				.set("password", new DefaultPasswordService().encryptPassword(password)))){
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}
	
	/**
	 * 删除
	 * @return -1：删除失败，0：删除成功
	 */
	public void doDelete(){
		int id = getParaToInt(0,0);
		if(id!=0){
			Store store = storeService.findById(id);
			//先判断便利店如果上传了图片，则删除图片
			if(!StrKit.isBlank(store.getStr("thumb"))){
				try {
					deleteFromFtp(store.getStr("thumb"));
				} catch (IOException e) {
					logger.error("删除时，相关图片"+store.getStr("thumb")+"删除失败！");
					e.printStackTrace();
				}
			}
			//然后再对记录进行删除
			store.delete();
			logger.info("删除便利店【"+id+"】，及其图片");
			renderSuccess();
			return;
		}
		renderFailed();
	}
	
	/**
	 * 根据省市县以及店铺名称查询店铺
	 */
	public void list(){
		int province = getParaToInt("p",0);
		int city = getParaToInt("c",0);
		int area = getParaToInt("a",0);
		String title = getPara("t");
		renderResult(0,storeService.find( province, city, area,title));

	}
}
